//
//  RSSPercistenceService.m
//  tv3rss
//
//  Created by Job Search on 04/08/14.
//  Copyright (c) 2014 responsfabrikken. All rights reserved.
//

#import "RSSPersistenceService.h"
#import "RSSItem.h"
#import "RSSItemCustom.h"




@implementation RSSPersistenceService

@synthesize managedObjectContext = _managedObjectContext;


+(RSSPersistenceService *)  initRSSPersistenceService:  (NSManagedObjectContext *)  mangedObjectCotext{
    static RSSPersistenceService *rss_persistence = nil;
    @synchronized(self) {
        if (rss_persistence == nil)
            rss_persistence = [[self alloc] init];
    }
    rss_persistence.managedObjectContext =  mangedObjectCotext;
    
    return rss_persistence;
}



-(NSMutableArray *)         fetchRSSItemsFromDB
{
    NSError *error;
    self.itemList = [[NSMutableArray alloc] init];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityDes = [NSEntityDescription entityForName:@"RSSItem" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entityDes];
    NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    for (RSSItem *item in fetchedObjects) {
        RSSItemCustom *rssItem    =   [[RSSItemCustom alloc] init];
        rssItem.link        =   [item valueForKey:@"link"];
        rssItem.title       =   [item valueForKey:@"title"];
        [self.itemList addObject:rssItem];
    }
    if (![[self managedObjectContext] save:&error]) {
        NSLog(@"Whoops, couldn't fetch: %@", [error localizedDescription]);
    }
    return self.itemList;
}



-(void)                     saveRSSItemsToDB:           (NSMutableArray *) items
{
    for (RSSItemCustom *item in items){
        RSSItem *rssItem = [NSEntityDescription insertNewObjectForEntityForName:@"RSSItem" inManagedObjectContext:[self managedObjectContext]];
        [rssItem setValue:item.title forKey:@"title"];
        [rssItem setValue:item.link  forKey:@"link"];
    }
    
    NSError *error;
    if (![[self managedObjectContext] save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }
}



- (void) clearRSSItemsFromDB
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"RSSItem" inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSError *error;
    NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
    
    
    for (NSManagedObject *managedObject in items) {
    	[_managedObjectContext deleteObject:managedObject];
    }
    if (![_managedObjectContext save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);

    }
}



-(BOOL)                     rssItemExistsInDB:          (NSString*)        pubDate
{
    //not implemented
    return YES;
}

@end
